﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; 
using System;
using System.Collections.Generic;
using System.Text;
using XW.Web.Framework.Extensions;
using XW.Utils;
namespace XW.Web.Framework.Extensions
{
    public static class AuthenticationServiceCollectionExtensions
    {
        public static AuthenticationBuilder AddSxAuthentication(this IServiceCollection services,IConfiguration config = null) {
            services.AddPermissions();
            return services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o => {
                    if (config != null)
                    {
                        var option = new CookieConfigOption();
                        config.Bind(option);
                        if (option.CookieName.IsNotNullOrEmpty())
                        {
                            o.Cookie.Name = option.CookieName;
                        }

                        if (option.CookieName.IsNotNullOrEmpty())
                        {
                            o.Cookie.Name = option.CookieName;
                        }

                        if (option.AccessDeniedPath.IsNotNullOrEmpty())
                        {
                            o.AccessDeniedPath = option.AccessDeniedPath;
                        }

                        if (option.LoginPath.IsNotNullOrEmpty())
                        {
                            o.LoginPath = option.LoginPath;
                        }

                        if (option.LogoutPath.IsNotNullOrEmpty())
                        {
                            o.LogoutPath = option.LogoutPath;
                        }

                        if (option.HttpOnly != null)
                        {
                            o.Cookie.HttpOnly = option.HttpOnly.Value;
                        }
                    }
                });
            //.AddCookie(o => {
            //    o.Cookie.Name = ".sxtoken"; // CookieName  授权的Cookie名字
            //    o.AccessDeniedPath = "/Home/Login";
            //    o.Cookie.HttpOnly = true;
            //    o.LoginPath = new PathString("/Home/Login");
            //});
        }
    }
}
